package pkg

import (
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func GitPull(name, url string)  {
	_, err := os.Open(name)
	if err!=nil {
		if os.IsNotExist(err) {
			Exec("git",getCurrentDirectory(),"clone",url)
		}
	}
	Exec("git",name,"pull")
}

func GitCheckout(name,version string) {
	Exec("git",name,"checkout" ,"-b",version,"origin/"+version)
}

func Exec(name , dir string ,args ...string) {
	cmd := exec.Command(name,args...)
	cmd.Dir = dir
	bytes,err := cmd.Output()
	if err != nil {
		if exitError,ok := err.(*exec.ExitError); ok {
			log.Println(string(exitError.Stderr))
		} else {
			log.Println(err.Error())
		}
	}
	resp := string(bytes)
	log.Println(resp)
}

func getCurrentDirectory() string {
	dir, _ := filepath.Abs(".")
	return strings.Replace(dir, "\\", "/", -1)
}